<?php
/**
 * Created by PhpStorm.
 * User: Drunk
 * Date: 2017-1-12
 * Time: 7:26
 */

namespace member;

use dce\feedback;
use think\Db as db;

abstract class captain{
    private static $_map = [],
        $_session_key = 'member_login',
        $_noop;

    public static function login($account, $password, $bit = 0){
        $info = self::exists($account, $password);
        if (empty($info)) return feedback::false('账号不存在或密码错误！');
        if ($info['is_banned']) return feedback::false('您已被禁止登录！');
        if ($info['is_deleted']) return feedback::false('帐号已删除！');
        self::log($info);
        return true;
    }

    public static function log($info){
        if (empty($info)) return false;
        $data_update = [
            'cnt_login' => $info['cnt_login'] + 1,
            'time_last_login' => date('Y-m-d H:i:s'),
        ];
        self::dao_member()->where('id', $info['id'])->update($data_update);
        session(self::$_session_key, $info);
    }

    /**
     * 取登录会员信息
     * @param null $field_name
     * @return mixed
     */
    public static function info($field_name = null){
        $info = session(self::$_session_key);
        return is_null($field_name) ? $info : $info[$field_name];
    }

    public static function logout(){
        session(self::$_session_key, null);
    }

    public static function is_logged(){
        return !empty(session(self::$_session_key));
    }

    public static function exists($username, $password){
        $where = ['password' => self::password_encrypt($password)];
        if (is_numeric($username)) {
            $field = \reglib::match_mobile($username) ? 'mobile' : 'id';
            $where[$field] = $username;
        } elseif (\reglib::match_email($username)) {
            $where['email'] = $username;
        } else {
            $where['username'] = $username;
        }
        return self::dao_member()->where($where)->find() ;
    }

    /**
     * encrypt the password
     * @param string $password
     * @param string $interference
     * @return string
     */
    public static function password_encrypt($password, $interference = 'FSdR#$t#%#wFsdt$E6$^$SDa#$%#3') {
        $interference .= '2426iou.' ;
        return sha1(sha1($password) . $interference);
    }

    public static function __callStatic($name, $arguments){
        if (preg_match('/^_?dao_(\w+)/ui', $name, $dao)) {
//            $dao_name = '_dao_' . $dao[1];
//            if (!array_key_exists($dao_name, self::$_map)) self::$_map[$dao_name] = db::table($dao[1]);
            return db($dao[1]);
        }
    }
}